package com.learn.seven;

import org.apache.log4j.Logger;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author ln
 * @Description: ${todo}
 * @date 2020/12/15
 */
public class TestReentrantLockWithCondition {
    static final Logger log = Logger.getLogger(TestReentrantLockWithCondition.class);

    static boolean hasCigarette = false;
    static boolean hasTakeout = false;

    static ReentrantLock reentrantLock = new ReentrantLock();
    //    等待烟的休息室
    static Condition waitCigaretteSet = reentrantLock.newCondition();
    //    等外卖的休息室
    static Condition waitTakeoutSet = reentrantLock.newCondition();

    public static void main(String[] args)  {

        new Thread(() -> {
            reentrantLock.lock();
            try {
                log.debug("有烟没？" + hasCigarette);
                while (!hasCigarette) {//没有烟
                    log.debug("没烟，先歇会");
                    try {
                        waitCigaretteSet.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                log.debug("有烟可以干活了");
            } finally {
                reentrantLock.unlock();
            }
        }, "小南").start();

        new Thread(() -> {
            reentrantLock.lock();
            try {
                log.debug("外卖到没？" + hasTakeout);
                while (!hasTakeout) {
                    try {
                        waitTakeoutSet.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                log.debug("外卖到了，可以干活了");
            } finally {
                reentrantLock.unlock();
            }
        }, "小女").start();

//        TimeUnit.SECONDS.sleep(1);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

//        送外卖的线程
        new Thread(() -> {
            reentrantLock.lock();
            try {
                hasTakeout = true;
                waitTakeoutSet.signal();
            } finally {
                reentrantLock.unlock();
            }
        }, "送外卖的线程").start();

//        TimeUnit.SECONDS.sleep(1);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


        new Thread(() -> {
            reentrantLock.lock();
            try {
                hasCigarette = true;
                waitCigaretteSet.signal();
            } finally {
                reentrantLock.unlock();
            }
        }, "送烟的线程").start();

    }
}
